import { PERMISSIONs_KEY } from '@app/constants/decorator.key';
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(PERMISSIONs_KEY, [context.getHandler()]);

    if (!requiredPermissions) {
      return true;
    }

    const { users } = context.switchToHttp().getRequest();
    return requiredPermissions.every((permission) => users.permissions?.includes(permission));
  }
}
